﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AzureProvider.ssdsClient;

namespace AzureProvider.SoupMethods
{
    public class PostNotify
    {
        public string Id;
        public Guid PostId;
        public string NotifyAddress;
    }

    public class PostNotifyMethods : PostRelatedMethods
    {

        protected override string containerId
        {
            get { return "Posts"; }
        }

        protected override string kind
        {
            get { return "PostNotify"; }
        }

        public PostNotify[] CreatePostTag(string PostID, string[] NotifyAddresses)
        {
            List<PostNotify> pt = new List<PostNotify>();
            foreach (string str in NotifyAddresses)
            {
                pt.Add(new PostNotify
                {
                    Id = GetId(PostID,str),
                    PostId = new Guid(PostID),
                    NotifyAddress = str
                });
            }
            return pt.ToArray();
        }

        protected override Entity CreateEntity(object Object)
        {
            PostNotify myobj = (PostNotify)Object;

            var entity = new Entity()
            {
                Id = myobj.Id ,
                Kind = kind
            };

            entity.Properties = new Dictionary<string, object>();
            entity.Properties.Add("NotifyAddress", myobj.NotifyAddress);
            entity.Properties.Add("PostId", myobj.PostId.ToString());

            return entity;
        }

        public override object CreateObject(Entity Entity)
        {
            PostNotify myObj = new PostNotify();
            myObj.Id = Entity.Id;
            myObj.NotifyAddress = (string)Entity.Properties.Single(tt => tt.Key == "NotifyAddress").Value;
            myObj.PostId = new Guid((string)Entity.Properties.Single(tt => tt.Key == "PostId").Value);

            return myObj;
        }

        private string GetId(string PostId, string NotifyAddresses)
        {
            string errMessage;
            PostNotify myobj =
                GetPostNotifies(PostId, out errMessage).SingleOrDefault(p => p.NotifyAddress == NotifyAddresses);
            if (myobj != null)
                return myobj.Id;
            else
                return Guid.NewGuid().ToString();

        }

        public IEnumerable<PostNotify> GetPostNotifies(string PostId, out string errMessage)
        {
            string qry = null;
            if (PostId != null)
                qry = string.Format(" from e in entities where e.Kind == \"{0}\" && e[\"PostId\"] == \"{1}\"  select e", kind, PostId);
            return base.GetObjects(qry, out errMessage).Cast<PostNotify>();
        }
    
    }
}
